package com.haoshuang.zhouzhoubang.ui.page.order.take

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.RegexUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivityTakeOrderBinding
import com.haoshuang.zhouzhoubang.ui.page.area.ServiceAreaActivity
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.haoshuang.zhouzhoubang.ui.page.order.take.code.PayCodeActivity
import com.haoshuang.zhouzhoubang.ui.page.order.take.preview.TakeOrderPreviewActivity
import com.haoshuang.zhouzhoubang.ui.page.order.take.record.TakeOrderRecordActivity
import com.haoshuang.zhouzhoubang.ui.page.order.take.services.ChooseServicesActivity
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.haoshuang.zhouzhoubang.utils.WeChatShareUtil
import com.haoshuang.zhouzhoubang.utils.WeChatShareUtil.Companion.weChatShareUtil
import com.lnkj.jialubao.utils.AccountUtils
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.visibleOrGone

/**
 *  门店下单
 */
class TakeOrderActivity : BaseVMActivity<TakeOrderViewModel, ActivityTakeOrderBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<TakeOrderActivity>()
        }
    }

    private var topIsMeal = 0 // 是否是套餐
    private var is_hourly_worker = 0
    private var serviceId = ""
    private var serviceName = ""
    private var servicePrice = ""
    private var serviceSuk = ""
    private var serviceCateId = ""
    private var serviceImage = ""
    private var key_areas = "" // 重点服务区域

    // 预约时间
    private var service_day = ""
    private var service_day1 = ""
    private var service_time = ""

    // 选择地区
    private var city1 = ""
    private var city2 = ""
    private var city3 = ""
    private var province_id = ""
    private var city_id = ""
    private var area_id = ""

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarColor(R.color.white)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.titleBar.title = "门店下单"
        binding.titleBar.leftImageView().click { finish() }

        binding.tvTeamTakeOrderRule.click {
            startPage<HelpDetailActivity>(
                "title" to "门店下单规则",
                "url" to "${URLConstants.baseUrl}index/index/agreement?id=28"
            )
        }

        // 选择服务
        binding.llChooseService.clickWithTrigger {
            startPageForResult<ChooseServicesActivity> { code, data ->
                if (code == 200 && data != null) {
                    serviceId = data.getString("id")
                    serviceName = data.getString("name")
                    serviceSuk = data.getString("spec")
                    servicePrice = data.getString("price")
                    serviceCateId = data.getString("cate_id")
                    serviceImage = data.getString("image")
                    key_areas = data.getString("key_areas")
                    is_hourly_worker = data.getIntExtra("is_hourly_worker", 0)
                    topIsMeal = data.getIntExtra("topIsMeal", 0)

                    binding.tvChooseService.text = "$serviceName"
                    binding.tvServicePrice.text = servicePrice
                    binding.llKeyArea.visibleOrGone(key_areas.isNotEmpty())
                    binding.tvKeyArea.text = key_areas
                }
            }
        }

        // 选择时间
        binding.llChooseServiceTime.clickWithTrigger {
            if (serviceId.isEmpty() || serviceCateId.isEmpty()) {
                toast("请选择服务")
                return@clickWithTrigger
            }
            startPageForResult<UpdateServiceTimeActivity>("cate_id" to serviceCateId) { code, data ->
                if (code == Activity.RESULT_OK) {
                    if (data != null) {
                        service_day = data.getStringExtra("service_day").toString()
                        service_day1 = data.getStringExtra("service_day1").toString()
                        service_time = data.getStringExtra("service_time").toString()
                        binding.tvChooseServiceTime.text = "$service_day1 $service_time"
                    }
                }
            }
        }

        // 选择地区
        binding.llChooseAddress.clickWithTrigger {
            startPageForResult<ServiceAreaActivity>(
                "city1" to city1, "city3" to city3, "city2" to city2, "isMultiple" to false
            ) { code, data ->
                if (code == 200 && data != null) {
                    city1 = data.getStringExtra("city1").toString()
                    city2 = data.getStringExtra("city2").toString()
                    city3 = data.getStringExtra("city3").toString()
                    province_id = data.getStringExtra("city1_id").toString()
                    city_id = data.getStringExtra("city2_id").toString()
                    area_id = data.getStringExtra("city_id").toString()
                    binding.tvChooseAddress.text = "$city1 $city2 $city3"
                }
            }
        }

        // 下单记录
        binding.tvTakeOrder.clickWithTrigger {
            startPage<TakeOrderRecordActivity>()
        }

        // 提交订单
        binding.tvPreview.clickWithTrigger {

            val add_pay_price = binding.etIncreasedAmount.text.toString()
            val discount_pay_price = binding.etDiscountAmount.text.toString()
            val detail = binding.etAddress.text.toString()
            val house_number = binding.etHouseNumber.text.toString()
            val user_phone = binding.etCustomerPhone.text.toString()
            val real_name = binding.etCustomerName.text.toString()
            val mark = binding.etRemark.text.toString()

            if (serviceId.isEmpty()) {
                toast("请选择服务")
                return@clickWithTrigger
            }
            if (service_day.isEmpty() || service_time.isEmpty()) {
                toast("请选择服务时间")
                return@clickWithTrigger
            }
            if (city1.isEmpty() || city2.isEmpty() || city3.isEmpty()) {
                toast("请选择服务地区")
                return@clickWithTrigger
            }
            if (detail.isEmpty()) {
                toast("请输入详细地址")
                return@clickWithTrigger
            }
            if (house_number.isEmpty()) {
                toast("请输入门牌号")
                return@clickWithTrigger
            }
            if (user_phone.isEmpty()) {
                toast("请输入手机号")
                return@clickWithTrigger
            }
            if (!RegexUtils.isMobileExact(user_phone)) {
                toast("请输入正确的手机号")
                return@clickWithTrigger
            }
            if (real_name.isEmpty()) {
                toast("请输入姓名")
                return@clickWithTrigger
            }

            // 开启预览窗口
            startPageForResult<TakeOrderPreviewActivity>(
                "province" to city1,
                "city" to city2,
                "area" to city3,
                "address" to detail,
                "houseNumber" to house_number,
                "phoneNumber" to user_phone,
                "customerName" to real_name,
                "serviceDay" to service_day1,
                "serviceTime" to service_time,
                "serviceImage" to serviceImage,
                "serviceName" to serviceName,
                "serviceSuk" to serviceSuk,
                "servicePrice" to servicePrice,
                "increasedAmount" to add_pay_price,
                "discountAmount" to discount_pay_price,
                "remark" to mark,
                "key_areas" to key_areas,
            ) { code, data ->
                if (code == 200) {
                    // 确认成功, 去创建订单
                    vm.teamAddOrder(
                        product_id = serviceId,
                        suk_unique = serviceSuk,
                        pay_price = servicePrice,
                        add_pay_price = add_pay_price,
                        discount_pay_price = discount_pay_price,
                        service_day = service_day,
                        service_time = service_time,
                        user_phone = user_phone,
                        real_name = real_name,
                        mark = mark,
                        province_id = province_id,
                        city_id = city_id,
                        area_id = area_id,
                        detail = detail,
                        house_number = house_number,
                        key_areas = key_areas,
                    )
                }
            }

        }
        binding.tvShare.clickWithTrigger {
            if (serviceId.isEmpty()) {
                toast("请选择服务")
                return@clickWithTrigger
            }
            // 服务id 是否是小时工 门店店长id
            val uid = AccountUtils.user?.uid
            val path =
                if (topIsMeal == 1) "/pagesA/noticeDetails/noticeDetails?id=${serviceId}&is_hourly_worker=${is_hourly_worker}&self_team_id=$uid" else "/pages/index/skill-detail/skill-detail?id=${serviceId}&is_hourly_worker=${is_hourly_worker}&self_team_id=$uid"
            // 获取缩略图
            Glide
                .with(this)
                .asBitmap()
                .load(serviceImage)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {

                        WeChatShareUtil.getInstance(mActivity)?.shareMiniProgram(
                            "$serviceName",
                            resource,
                            "分享服务下单",
                            path
                        )
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {

                    }

                })


        }

    }

    override fun initData() {
    }

    override fun startObserve() {
        vm.teamAddOrderData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                // 打开海报付款页面
                val sn = it?.order_id
                startPage<PayCodeActivity>("orderSn" to sn)
                finish()
            }
        }
    }

}